package com.gpl.service;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class IOVServerHandler extends ChannelInboundHandlerAdapter {

    private Map<String, Channel> activeChannel = new ConcurrentHashMap<>();//正在连接的通道
    private Map<String, Channel> activeVin = new ConcurrentHashMap<>();//正在上报的车辆

    public Map<String, Channel> getActiveChannel() {
        return activeChannel;
    }

    public Map<String, Channel> getActiveVin() {
        return activeVin;
    }

    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        activeChannel.put(ctx.channel().id().asShortText(),ctx.channel());
        System.out.println(ctx.channel() + " Active");
        System.out.println(activeChannel);
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel() + " Inactive");
        ctx.fireChannelInactive();
    }

    @Override// 每次读取消息调用
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("IOVServerHandler:" + Thread.currentThread().getName());
        String msg_1 = (String) msg;
        System.out.println(msg_1);
        //解析llll
       if(msg_1.startsWith("vehicle_start:")){
           String vin = msg_1.substring(14);
           activeVin.put(vin,ctx.channel());
           redisTemplate.opsForHash().put(ctx.channel().id().asShortText(),vin,ctx.channel());
        } else if (msg_1.startsWith("vehicle_stop:")) {
           String vin = msg_1.substring(13);
           activeVin.remove(vin);
       } else if (msg_1.startsWith("vehicle_msg:")) {
           String body = msg_1.substring(29);
           System.out.println(body);
       }else if (msg_1.equals("close")){
           activeChannel.remove(ctx.channel().id().asShortText());
        }


        //自己处理业务
        //发送Kafka
        //Hbase
    }
    @Override// 通知读取消息完毕
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }
    @Override//处理异常
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


}
